<?php
include ('./mysqli_connect.php');
include('./Session.php');
include ('./functions.php');

if(isset($_REQUEST['mess']) and isset($_GET['gid']) and filter_var($_GET['gid'],FILTER_VALIDATE_INT)){
    $chattext = mysqli_real_escape_string($dbc, $_REQUEST['mess']);
    $gid = $_GET['gid'];
    $query = "INSERT INTO `chat`(`group_id`,`user_id`,`chat_mess`,`chat_time`) VALUES({$gid},{$_SESSION['uid']},'{$chattext}',NOW())";
    $result = mysqli_query($dbc, $query);
    $query = "SELECT count(chat_id) FROM `chat` WHERE `group_id`={$gid}";
    $result = mysqli_query($dbc, $query);
    if(mysqli_num_rows($result)>0){
        list($num_row) = mysqli_fetch_array($result,MYSQLI_NUM);
        if($num_row<=5){
            $num_begin= 0;
        }else{
            $num_begin = $num_row-5;
        }
    }
    $querys = "SELECT u.user_id,u.user_name,u.user_avatar,u.user_online,c.chat_mess,DATE_FORMAT(c.chat_time,'%h:%i:%s %p') as time "
            . " FROM `user` as u INNER JOIN `chat` as c USING(user_id) "
            . " WHERE c.group_id = {$gid} ORDER BY c.chat_time ASC LIMIT {$num_begin},4";
    $results = mysqli_query($dbc, $querys);
    if(mysqli_num_rows($results)>0){
    while($chat = mysqli_fetch_array($results,MYSQLI_ASSOC)){
        echo "<div class='chat-line'>
            <div class='user-info'>
                <div class='cbox-user-img'>
                    <img src='Images/Uploads/".show_avatar($chat['user_avatar'])."' width='50' alt='user-avatar'>
                </div>
            <div class='cbox-message'>
                {$chat['chat_mess']}
            </div>
            </div>
            <div class='user-info-line'>                            
            <div class='cbox-user-name'>
                    ".ucfirst($chat['user_name'])."
                </div>
            <div class='cbox-time'>
                {$chat['time']}
            </div>
            </div>
        </div><!-- end chat-line -->";
    }      
    }
}else{
    echo "<p>error</p>";
}
